package translationTable;

import symbol.SymbolTable;
import syntaxtree.Counter;

/**
 * 
 * @author Benoit
 */
public class ObjectSpec {
    /**
     * Type of the object.
     */
    private String type = null;
    /**
     * Identifier of the object.
     */
    private String id;
    
    private boolean primitive = false;
    
    public ObjectSpec(String type, String id){
        this.type = type;
        this.id = id;
    }
    
    public ObjectSpec(String id){
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public String getType() {
        if(this.type == null)
            this.type = this.findType();
        return this.type;
    }
    
    private String findType(){  
        String ref = this.id;
        SymbolTable st = SymbolTable.getInstance();
        if(ref.length() > 2 && ref.substring(0, 3).equals("new")){            
            ref = ref.replaceAll("new","");
            ref = ref.split("\\(")[0];
        }else if(st.contains(ref)){               
            return st.get(ref).getClosestState(Counter.getInstance().getInst()).getType();
        }else if(st.equals("this")){              
            return st.getClassName();             
        }else{
            this.primitive = true;
            return this.getPrimitiveType(id);
        }
        return ref;
    }

    public boolean isPrimitive() {
        this.findType();
        return primitive;
    }
    
    private String getPrimitiveType(String id){
        try{
            Integer.parseInt(id);
            return "int";                     
        }catch(NumberFormatException e){
            try{
                Double.parseDouble(id);
                return "double";
            }catch(NumberFormatException e1){
                try{
                    Float.parseFloat(id);
                    return "float";
                }catch(NumberFormatException e2){                    
                    Boolean.parseBoolean(id);
                    return "boolean";
                }
            }
        }
    }
}